package com.tech.koufu.ui.view;

 
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap; 
import java.util.Map; 

import cn.sharesdk.framework.ShareSDK;

import com.tech.koufu.MainActivity;
import com.tech.koufu.MyApplication;
import com.tech.koufu.R;
import com.tech.koufu.model.StockInfo;
import com.tech.koufu.model.UserInfo;
import com.tech.koufu.model.UserStocks;
import com.tech.koufu.tools.HttpUtils;
import com.tech.koufu.tools.KouFuTools; 
import com.tech.koufu.ui.activity.EntrustListActivity;
import com.tech.koufu.ui.activity.SellStocksListActivity;
import com.tech.koufu.ui.activity.TeamChangeActivity;
import com.tech.koufu.ui.adapter.MainStocksAdapter;
import com.umeng.analytics.MobclickAgent;

import extras.com.handmark.pulltorefresh.library.PullToRefreshBase;
import extras.com.handmark.pulltorefresh.library.PullToRefreshListView;
import extras.com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import extras.com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener; 
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment; 
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;  
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
/**
 * 首页  用户登录后
 * @author luo
 *
 */
public class MainContentFragment extends Fragment implements OnClickListener{
	private static final String TAG = MainContentFragment.class.getName();
	private static final int MSG_USERINFO = 1; //用户信息
	private static final int MSG_STOCK_LIST = 2; //股票列表
	private static final int MSG_TIME_RUN = 3; //当前时间
	private static final int MSG_KAIPAN = 4; //开盘时间
	private static final int REFRESH_FINISH = 5; //刷新完成
//	private StringRequest stringRequest;
//	private RequestQueue mQueue;
	private View view;
	private MyApplication myApp;
//	private Message msg = new Message();
	private PullToRefreshListView mPullToRefreshListView;
	private ListView actualListView;
	private MainStocksAdapter mStocksAdapter;

	public UserInfo info = new UserInfo();
	private UserStocks ustocks;
	private StockInfo stocks;
	private StringBuilder stockparms = new StringBuilder();
	private Map<String,String> data;
	private TextView txt_main_mycount,txt_profit_rate,txt_total_money,
	txt_stock_price,txt_used_funds,txt_day_gains,txt_main_datetime;
	private TextView txt_main_timetitle; //开盘时间
	public ArrayList<UserStocks> list ;
	private ArrayList<StockInfo> datas;
	private String timeReader,kaipanCount;
	MainActivity mainActivity ;
	private boolean isF5 = false;
	private View lvTop;
//	private LinearLayout ly_main_pull_title;
//	private TextView tv_main_pull_title;
	private Thread kpThread,dateTimeRun;
	private boolean isKpThread, isDateTime; 
	public static MainContentFragment getInstance(String tag){ 
		MainContentFragment frg = new MainContentFragment();
		Bundle bundle = new Bundle();
		bundle.putString("tag", tag);
		frg.setArguments(bundle);
		return frg;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) { 
		if (view == null) { 
			view = inflater.inflate(R.layout.fragment_main_content, container,
					false);
			mainActivity = (MainActivity) getParentFragment().getActivity();
			myApp = (MyApplication)getActivity().getApplication();
			initView();
		} else { 
		}
		// 缓存的rootView需要判断是否已经被加过parent，
		// 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
		ViewGroup parent = (ViewGroup) view.getParent();
		if (parent != null) {
			parent.removeView(view);
		}
  
		return view;
	}
	
	 @Override
	public void onResume() { 
		super.onResume();
		Log.d(TAG, "~~~~~~~~MainContentFragment~~onResume ~~~~~");
		ShareSDK.initSDK(getActivity().getApplicationContext());
		MobclickAgent.onPageStart("MainContent"); 
	}
	 
	 @Override
	public void onPause() { 
		super.onPause();
		MobclickAgent.onPageEnd("MainContent");  
		Log.d(TAG, "~~~~~~~~MainContentFragment~~onPause ~~~~~");
	}
	 
	long stime ;
	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		stime = System.currentTimeMillis();
		getUserInfo();
		initData();
		
		isDateTime = true;
		DateTimeRun(); 
		dateTimeRun.start();
		
		isKpThread = true;
		kaipanCount(); 
		kpThread.start();
			
		mainActivity.ly_main_pull_title.setVisibility(View.VISIBLE); 
	}
	
	public void initView() { 
		mPullToRefreshListView = (PullToRefreshListView)view.findViewById(R.id.lv_stocks);
		actualListView = mPullToRefreshListView.getRefreshableView(); 
		registerForContextMenu(actualListView);

		lvTop = LayoutInflater.from(getActivity().getApplicationContext()).inflate(R.layout.item_main_lv_top, null);
		actualListView.addHeaderView(lvTop,null,false);
		
		lvTop.findViewById(R.id.btn_buy_stock).setOnClickListener(this);
		lvTop.findViewById(R.id.btn_sell_stock).setOnClickListener(this);
		lvTop.findViewById(R.id.btn_etrust).setOnClickListener(this);
		mainActivity.ly_main_pull_title.setOnClickListener(this);
		
		txt_main_mycount = (TextView)view.findViewById(R.id.txt_main_mycount);
		txt_profit_rate = (TextView)lvTop.findViewById(R.id.txt_profit_rate);
		txt_total_money = (TextView)lvTop.findViewById(R.id.txt_total_money);
		txt_stock_price = (TextView)lvTop.findViewById(R.id.txt_stock_price);
		txt_used_funds = (TextView)lvTop.findViewById(R.id.txt_used_funds);
		txt_day_gains = (TextView)lvTop.findViewById(R.id.txt_day_gains);
		txt_main_datetime = (TextView)view.findViewById(R.id.txt_main_datetime);
		txt_main_timetitle = (TextView)view.findViewById(R.id.txt_main_timetitle);
	}
	private void initData(){
		datas = new ArrayList<StockInfo>();
		list = new ArrayList<UserStocks>();
		mStocksAdapter = new MainStocksAdapter(getActivity().getApplicationContext(),list);
		actualListView.setAdapter(mStocksAdapter);		
		mStocksAdapter.notifyDataSetChanged();
		mPullToRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {

			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) { 
				Mode mode = mPullToRefreshListView.getCurrentMode(); 
		        if(mode == Mode.PULL_FROM_START) { 
		        	 refreshData(); 
		        }  
			}
		});  
	}
	public void refreshData(){  
		isF5 = true;
		stockparms = null;
		stockparms = new StringBuilder();
		datas.clear();
		list.clear();
		if(mStocksAdapter!=null)
			mStocksAdapter.notifyDataSetChanged();
		getUserInfo();  
		
	}
	
	/**
	 * 登录成功后 获取用户信息
	 */
	private void getUserInfo(){
		new Thread(new Runnable() {

			@Override
			public void run() { 
				String t = KouFuTools.readTimeInfo(new String());
				myApp = (MyApplication)getActivity().getApplication();
				data = new HashMap<String, String>();
				data.put("userid", myApp.getUserid());
				data.put("group_id", myApp.getGroupId());
				data.put("username", myApp.getUserName());
				data.put("nickname", myApp.getUserName());
				data.put("time", t);
				data.put("login", "1");
				data.put("flag", "0");
				String cookie = KouFuTools.descrypt(myApp.getUserid() + t );
//				final String user = HttpUtils.postRequest(myApp.url+"Userinfo.dll", cookie ,data);
				final String user = HttpUtils.postRequest(myApp.url+"userinfotest.dll", cookie ,data);
//								Log.w("UserInfo=====>", user);
								Log.w("getUserInfo~~ URL & Params===>", myApp.url + data.toString());
				if (user!=null && user.substring(0,1).equals("0")) {
					parseUserInfoJsonString(user);
					if(!(user.substring(user.lastIndexOf("|"), user.length())).equals("|") && 
							user.substring(user.lastIndexOf("|"), user.length()) !=null){

						parseStocksInfoJsonString(user);

					}
				}else{
					mHandler.post(new Runnable() {
						
						@Override
						public void run() { 
							if(user!=null)
								Toast.makeText(getActivity(),user.substring(2) , Toast.LENGTH_SHORT).show();
							else{
								Toast.makeText(getActivity(),"登录失败" , Toast.LENGTH_SHORT).show();
							}
							mPullToRefreshListView.onRefreshComplete();
						}
					});
					
				}
				 
			}
		}).start();
	}

	/**
	 * 用户数据解析 
	 * @param returnValue
	 */
	private void parseUserInfoJsonString(String returnValue){
		if (returnValue!=null && returnValue.substring(0, 1).equals("0")) {
			String[] us = returnValue.trim().substring(2, returnValue.lastIndexOf("|")).split(",");
//			Log.v("MainContent=====>", returnValue.substring(2, returnValue.lastIndexOf("|")).toString());
			info.setTeamid(us[0].toString());
			info.setXzmc(us[1].toString());
			info.setZqlb(us[2].toString());
			String[] money = us[3].toString().split("\\|");
			info.setBeginMoney(money[0].toString());
			info.setCanUseMoney(money[1].toString());
			info.setAllMoney(us[4].toString());
			info.setRjyl(us[5].toString());
			info.setRyl(us[6].toString());
			info.setZyl(us[7].toString());
			info.setYyl(us[8].toString());
			info.setYll(us[9].toString());
			info.setCgl(us[10].toString());
			info.setZzl(us[11].toString());
			info.setPm(us[12].toString());
			info.setSj(us[13].toString());
			info.setCw(us[14].toString());
			info.setPj(us[15].toString());  
			myApp.mUserInfo = info;
			myApp.setTeamid(us[0].toString());
			mHandler.sendEmptyMessage(MSG_USERINFO);

		}else {
			mHandler.post(new Runnable() {
				
				@Override
				public void run() { 
					Toast.makeText(getActivity(), "返回数据失败，请重新刷新页面", Toast.LENGTH_LONG).show();
				}
			});
			
		}
	}

	/**
	 * 股票数据解析
	 * @param returnValue
	 */
	private void parseStocksInfoJsonString(String returnValue){
		if (returnValue.substring(0, 1).equals("0")) {
			String[] us = returnValue.trim().substring(returnValue.lastIndexOf("|")+1,returnValue.length()).split(";");
			Log.v("MainContent=====>", 
					returnValue.substring(returnValue.lastIndexOf("|"),returnValue.length()).toString());
			if(isF5){
				list.clear();
			}
			stockparms = new StringBuilder();
			for(int i=0;i<us.length;i++){
				ustocks = new UserStocks();
				String[] a =  us[i].split(",");
				if(a.length > 0){
					ustocks.setStockId(a[0].toString().trim());
					ustocks.setStockName(a[1].toString().trim());
					ustocks.setStockHold(a[2].toString().trim());
					ustocks.setStockCanSell(a[3].toString().trim());
					ustocks.setStockbj(a[4].toString().trim());
					ustocks.setStockykj(a[5].toString().trim());
				}
				ustocks.setAllmoney(info.getAllMoney());
				ustocks.setTeamId(info.getTeamid());
				list.add(ustocks);
				stockparms.append(","+ustocks.getStockId());

			}
			myApp.mUserStocks = list; 
			if(stockparms.length()>1){
				getUserStocksInfo();
			}else{
				mHandler.obtainMessage(REFRESH_FINISH).sendToTarget();
			}
		}else{
			 mHandler.obtainMessage(REFRESH_FINISH).sendToTarget();
		}
	}

	/**
	 * 用户持股信息
	 */
	private void getUserStocksInfo(){
		new Thread(new Runnable() {			
			@Override
			public void run() { 
				if(stockparms!=null && !stockparms.equals("")){
//					String stocks = HttpUtils.getRequest(myApp.url+"BinStock.dll?stock="
//							+ stockparms.substring(1) +"&field=ZSP,JKP,CJE,ZG,ZD,ZX,BJ1,SJ1,CJL,SYL," +
//							"BL1,BJ2,BL2,BJ3,BL3,SL1,SJ2,SL2,SJ3,SL3,BJ4,BL4,BJ5,BL5,SJ4,SL4,SJ5,SL5");
					String stocks = HttpUtils.getRequest(myApp.url+"BinStock.dll?stock="
							+ stockparms.substring(1) +"&field=ZSP,JKP,CJE,ZG,ZD,ZX,CJL,SYL");
//					Log.v("UserStocksInfo=====>", stocks);
					parseBinStockString(stocks); 
				}
			}
		}).start();

	}

	/**
	 * 股票信息解析
	 * @param returnvalue
	 */
	private void parseBinStockString(String returnvalue){
		try {
			if(isF5){
				datas.clear();
			}
			String[] a = returnvalue.trim().split(";"); 
			int binStockLength = a.length; 
			for (int i = 0; i < binStockLength; i++) {
				String[] bs = a[i].split(",");
				int bsLength = bs.length; 
				stocks = new StockInfo(); 
				stocks.setCode(bs[0].toString().trim());
				if(bsLength==1){
					stocks.setName(list.get(i).stockName);
//					stocks.setZsp(KouFuTools.TAG_OFF_STOCK);
//					stocks.setJkp(KouFuTools.TAG_OFF_STOCK);
//					stocks.setCje(KouFuTools.TAG_OFF_STOCK);
//					stocks.setZg(KouFuTools.TAG_OFF_STOCK);
//					stocks.setZd(KouFuTools.TAG_OFF_STOCK);
//					stocks.setZx(KouFuTools.TAG_OFF_STOCK);		
//					stocks.setCjl(KouFuTools.TAG_OFF_STOCK);
//					stocks.setSyl(KouFuTools.TAG_OFF_STOCK);
					list.get(i).setStockdqj(KouFuTools.TAG_OFF_STOCK);
					list.get(i).setStockZsp(KouFuTools.TAG_OFF_STOCK); 
				}else{
					stocks.setName(bs[1].toString().trim());
					stocks.setZsp(bs[2].toString().trim());
					stocks.setJkp(bs[3].toString().trim());
					stocks.setCje(bs[4].toString().trim());
					stocks.setZg(bs[5].toString().trim());
					stocks.setZd(bs[6].toString().trim());
					stocks.setZx(bs[7].toString().trim());		
					stocks.setCjl(bs[8].toString().trim());
					stocks.setSyl(bs[9].toString().trim());
					list.get(i).setStockdqj(stocks.getZx());
					list.get(i).setStockZsp(stocks.getZsp()); 
				}		
//				stocks.setBj1(bs[8].toString().trim());
//				stocks.setSj1(bs[9].toString().trim());		
//				stocks.setBl1(bs[12].toString().trim());
//				stocks.setBj2(bs[13].toString().trim());
//				stocks.setBl2(bs[14].toString().trim());
//				stocks.setBj3(bs[15].toString().trim());
//				stocks.setBl3(bs[16].toString().trim());
//				stocks.setSl1(bs[17].toString().trim());
//				stocks.setSj2(bs[18].toString().trim());
//				stocks.setSl2(bs[19].toString().trim());
//				stocks.setSj3(bs[20].toString().trim());
//				stocks.setSl3(bs[21].toString().trim());
//				stocks.setBj4(bs[22].toString().trim());
//				stocks.setBl5(bs[23].toString().trim());
//				stocks.setBj5(bs[24].toString().trim());
//				stocks.setBl5(bs[25].toString().trim());
//				stocks.setSj4(bs[26].toString().trim());
//				stocks.setSl4(bs[27].toString().trim());
//				stocks.setSj5(bs[28].toString().trim());
//				stocks.setSl5(bs[29].toString().trim());
				datas.add(stocks);
				
			}  
			if (datas != null && datas.size() > 0) {
				mHandler.sendEmptyMessage(MSG_STOCK_LIST);
			}
		} catch (Exception e) { 
			e.printStackTrace();
		}

	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_buy_stock:
			Intent intent = new Intent(getActivity(),ChooseStockFragment.class); 
			intent.putExtra("userStock", list);
			startActivity(intent);
			break;
		case R.id.btn_sell_stock:
			intent = new Intent(getActivity(),SellStocksListActivity.class); 
			intent.putExtra("userStock", list);
			startActivity(intent);
			break;
		case R.id.btn_etrust:
			intent = new Intent(getActivity(),EntrustListActivity.class); 
			intent.putExtra("userStock", list);
			startActivity(intent);
			break;
		case R.id.ly_main_pull_title:
			intent = new Intent(getActivity(),TeamChangeActivity.class);
			getParentFragment().startActivityForResult(intent, 6);
		default:
			break;
		}

	}
 
	private Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) { 
			switch (msg.what) {
			case MSG_USERINFO:
				if(info.getCw().equals("空仓")){
					txt_main_mycount.setText("0.00%仓");
				}else {
					txt_main_mycount.setText(info.getCw() + "仓");
				}

				Float ylzj = Float.valueOf(info.getAllMoney()) - Float.valueOf(info.beginMoney);
				if(ylzj > 0){ //盈利大于初始资金 显示红色
					txt_profit_rate.setTextColor(getResources().getColor(R.color.stockUpColor));
					txt_total_money.setTextColor(getResources().getColor(R.color.stockUpColor));
					txt_stock_price.setTextColor(getResources().getColor(R.color.stockUpColor));
					txt_used_funds.setTextColor(getResources().getColor(R.color.stockUpColor));
					txt_day_gains.setTextColor(getResources().getColor(R.color.stockUpColor));
				}else{ //盈利低于初始资金  显示绿色
					txt_profit_rate.setTextColor(getResources().getColor(R.color.stockDownColor));
					txt_total_money.setTextColor(getResources().getColor(R.color.stockDownColor));
					txt_stock_price.setTextColor(getResources().getColor(R.color.stockDownColor));
					txt_used_funds.setTextColor(getResources().getColor(R.color.stockDownColor));
					txt_day_gains.setTextColor(getResources().getColor(R.color.stockDownColor));
				}
				DecimalFormat df =new DecimalFormat("00.00");
				String total_money = df.format(Float.valueOf(info.getAllMoney())); //保留小数点后两位
				String canUse_money = df.format(Float.valueOf(info.getCanUseMoney()));
				String stock_price = df.format(Float.valueOf(total_money) - Float.valueOf(canUse_money));
				txt_profit_rate.setText(info.getYll() + "%");
				txt_total_money.setText(total_money);
				txt_stock_price.setText(stock_price);
				txt_used_funds.setText(canUse_money);
				Float rgyl = Float.parseFloat(info.getRjyl());
				if(rgyl<1 && rgyl>0){
					txt_day_gains.setText("0" + info.getRjyl());
				}else if(rgyl>-1 && rgyl <0){
					txt_day_gains.setText("-0" + info.getRjyl().startsWith("."));
				}else{
					txt_day_gains.setText(info.getRjyl());
				}
				mainActivity.tv_main_pull_title.setText(info.getXzmc());
				//				loginPHP();
				Log.d(TAG, "首页表格数据，共加载了"+(System.currentTimeMillis()-stime)/1000+"s的时间");
				break;
			case MSG_STOCK_LIST: 
				isF5 = false;
				mainActivity.cancleRefreshRotate(); 
				if(mStocksAdapter==null){
					mStocksAdapter = new MainStocksAdapter(getActivity().getApplicationContext(),list);
					actualListView.setAdapter(mStocksAdapter);		
				}else{
					mStocksAdapter.stockinfo = list;
				}
				mStocksAdapter.notifyDataSetChanged();
				mPullToRefreshListView.onRefreshComplete();
				Log.d(TAG, "首页列表数据，共加载了"+(System.currentTimeMillis()-stime)/1000+"s的时间");
				break;
			case MSG_TIME_RUN:
				txt_main_datetime.setText(timeReader);
			case MSG_KAIPAN:
				txt_main_timetitle.setText(kaipanCount);
			case REFRESH_FINISH:
				mPullToRefreshListView.onRefreshComplete();
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}

	};

	/**
	 * 首页当前时间显示
	 */
	private void DateTimeRun(){
		dateTimeRun = new Thread(new Runnable() {

			@Override
			public void run() { 
				try {
					while(isDateTime){
						String today = null;
						String thour;
						String tminute;
						Calendar calendar = Calendar.getInstance();
						int day = calendar.get(calendar.DAY_OF_WEEK);
						if (day == 2) {
							today = "星期一";
						}else if (day == 3) {
							today = "星期二";
						}else if (day == 4) {
							today = "星期三";
						}else if (day == 5) {
							today = "星期四";
						}else if (day == 6) {
							today = "星期五";
						}else if (day == 7) {
							today = "星期六";
						}else if (day == 1) {
							today = "星期日";
						}
						int hour = calendar.get(calendar.HOUR_OF_DAY);
						if(hour>=0 && hour < 10){
							thour = "0" + hour;
						}else{
							thour = "" + hour;
						}
						int minute = calendar.get(calendar.MINUTE);
						if(minute >= 0 && minute < 10){
							tminute = "0" + minute;
						}else{
							tminute = "" + minute;
						}
						timeReader = (calendar.get(Calendar.MONTH)+1) + "/" + calendar.get(calendar.DAY_OF_MONTH) + "  "
								+ thour + ":" + tminute + "  " + today;
						Thread.sleep(1000); 
						mHandler.obtainMessage(MSG_TIME_RUN).sendToTarget();
					}
				} catch (InterruptedException e) { 
					e.printStackTrace();
				}
			}
		}) ;
	}

	private void kaipanCount(){ 
		try {
			kpThread = new Thread(new Runnable() {

				@Override
				public void run() {
					try {
						while(isKpThread){
							kaipanCount = KouFuTools.KaiPanTimeCount(); 
							Thread.sleep(1000*60); 
							mHandler.obtainMessage(MSG_KAIPAN).sendToTarget();
						}
					} catch (InterruptedException e) { 
						e.printStackTrace();
					} 
				}
			});
		} catch (Exception e) { 
			e.printStackTrace();
		}
	}
 

	
	@Override
	public void onStop() { 
		super.onStop();
		Log.d(TAG, "~~~~~~~~MainContentFragment~~onStop ~~~~~"); 
	}
	
	public void setKaiPanClock(boolean isOpen){ 
		isKpThread = isOpen;
		isDateTime = isOpen;
		if(isKpThread && kpThread!=null){
			kpThread = null;
			kaipanCount();
			kpThread.start();
		}else{ 
//			kpThread.interrupt();
		}
		if(isDateTime && dateTimeRun!=null ){
			dateTimeRun = null;
			DateTimeRun();
			dateTimeRun.start();
		}else{ 
//			dateTimeRun.interrupt();
		}
	}
	public void clearThread(){
		isKpThread = false;
		isDateTime = false; 
		kpThread = null;
		dateTimeRun = null; 
	}
}

